<template>
  <div>
    <el-card>
      <el-page-header icon="" title="产品管理">
        <template #content>
          <span class="text-large font-600 mr-3" style="font-size: 16px">
            添加产品
          </span>
        </template>
      </el-page-header>
      <el-form
        ref="productFormRef"
        style="max-width: 600px"
        :model="productForm"
        :rules="productFormRules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="产品名称" prop="title">
          <el-input v-model="productForm.title" />
        </el-form-item>
        <el-form-item label="产品简要描述" prop="introduction">
          <el-input v-model="productForm.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="产品详细描述" prop="detail">
          <el-input v-model="productForm.detail" type="textarea" />
        </el-form-item>
        <el-form-item label="产品图片" prop="cover">
          <Upload :avatar="productForm.cover" @uploadChange="handleChange" />
        </el-form-item>
        <el-form-item class="button-container" style="margin-left: 50px">
          <el-button type="primary" @click="submitForm()" class="custom-button">
            添加产品
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import Upload from "@/components/upload/Upload.vue";
import upload from "@/util/upload";
import { useRouter } from "vue-router";
const productFormRef = ref();
const productForm = reactive({
  title: "",
  introduction: "",
  detail: "",
  cover: "",
  file: null,
});

const productFormRules = reactive({
  title: [{ required: true, message: "请输入产品名字", trigger: "blur" }],
  introduction: [
    { required: true, message: "请输入简要描述", trigger: "blur" },
  ],
  detail: [{ required: true, message: "请输入详细描述", trigger: "blur" }],
  cover: [{ required: true, message: "请上传产品图片", trigger: "blur" }],
});

//每次选择完图片之后的回调
const handleChange = (file) => {
  productForm.cover = URL.createObjectURL(file);
  productForm.file = file; //把表单中放入原生的file对象
};

const router = useRouter();
const submitForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      //提交数据到后端
      await upload("/adminapi/product/add", productForm);
      // console.log(productForm);
      router.push("/product-manage/productlist");
    }
  });
};
</script>

<style scoped>
.demo-ruleForm {
  margin-top: 50px;
}
</style>
